import { isSameDomain } from "@/utils/url";

import { useAuthStore } from "@/store/useAuthStore";
import useLiveDataStore from "@/views/LiveNew/stores/LiveDataStore";
import { useUserStore } from "@/store/useUserStore";
import { useTencentIM } from "@/utils/tencent-im";
import { isWeChatBrowserPro } from "@/utils/wechat";
import { useLocationParams } from "@/store/useLocationStore";
import { useQuestionnaireStore } from "@/store/useQuestionnaireStore";

const handleAuth = to => {
  const { isAuthenticated } = useUserStore();
  if (!isAuthenticated() && !isSameDomain()) {
    const { handleAuth } = useAuthStore();
    handleAuth(to);
    return true;
  }
  return false;
};

const handleCodeCheck = async to => {
  const { code } = to.query;
  if (code) {
    const { removeParam, getAllParams } = useLocationParams();
    removeParam("code");
    const { login } = useUserStore();
    const data = await login({ ...getAllParams(), code });
    if (data) {
      return true;
    } else {
      return false;
    }
  }
  return true;
};

const handleEntryCheck = async to => {
  const liveDataStore = useLiveDataStore();
  if (isWeChatBrowserPro()) {
    try {
      const data = await liveDataStore.checkEntrance();
      if (data && data.errMsg) {
        if (data?.adjustmentParam) {
          const rediData =
            await useQuestionnaireStore().checkRoomWatchRecordResult(
              data?.adjustmentParam
            );
          if (rediData) {
            return rediData;
          }
        }
        return {
          name: "LiveCourseError",
          query: { ...data }
        };
      }
    } catch (error) {
      return false;
    }
  }
  return true;
};

const handleEntry = async to => {
  if (to.meta.needEntry) {
    const liveDataStore = useLiveDataStore();
    if (!liveDataStore.roomData) {
      try {
        const timeoutPromise = new Promise((_, reject) => {
          setTimeout(() => reject(new Error("Request timeout")), 10000); // 10秒超时
        });
        const data = await Promise.race([
          liveDataStore.fetchRoomData(to.query.rId),
          timeoutPromise
        ]);
        if (!data) {
          console.error("Failed to fetch room data");
          return false;
        }
        // 处理分享问题
        const { getParam } = useLocationParams();
        const userStore = useUserStore();
        liveDataStore.setShareUserId(getParam("shareUserId"));
      } catch (error) {
        console.error("Error in handleEntry:", error);
        return false;
      }
    }
  }
  return true;
};
const handleCountDown = async to => {
  const liveDataStore = useLiveDataStore();
  if (!liveDataStore.roomData) {
    await handleEntry(to);
  }
  const { streamStartTime } = liveDataStore.roomData;
  const now = new Date().getTime();
  const diff = new Date(streamStartTime).getTime() - now;
  if (diff > 0) {
    return {
      name: "LiveCountdown",
      query: to.query
    };
  }
  return true;
};
const checkReplay = async to => {
  const liveDataStore = useLiveDataStore();
  if (!liveDataStore.roomData) {
    await handleEntry(to);
  }
  const { openStartTime, openType } = liveDataStore.roomData.transcribe;
  if (openType == 0) {
    return true;
  }
  const now = new Date().getTime();
  const diff = now - new Date(openStartTime).getTime();
  if (diff > 0) {
    return {
      name: "LiveReplay",
      query: to.query
    };
  }
  return true;
};
const handleReplay = async to => {
  const liveDataStore = useLiveDataStore();
  const { openType } = liveDataStore.roomData.transcribe;
  if (openType === 0) {
    return {
      name: "Error",
      query: { ...to.query, message: "该直播未开启回放" }
    };
  }
  return true;
};
const handleWatchLive = async to => {
  const liveDataStore = useLiveDataStore();
  if (!liveDataStore.roomWatchData) {
    await liveDataStore.fetchRoomWatchData("REAL_TIME");
  }
  return true;
};
const handleWatchLiveReplay = async to => {
  const liveDataStore = useLiveDataStore();
  await liveDataStore.fetchRoomWatchData("PLAY_BACK");
  return true;
};
const handleCountDownIM = async to => {
  const { loginChat } = useTencentIM();
  const liveDataStore = useLiveDataStore();
  if (!liveDataStore.roomData) {
    await handleEntry(to);
  }
  if (liveDataStore.roomData?.hasBeforChat == 1) {
    loginChat({
      userSig: liveDataStore.roomData.userSig,
      groupID: liveDataStore.roomData.screeningId.toString()
    });
  }
  return true;
};
const handleLiveIM = async to => {
  const tencentIMStore = useTencentIM();
  const liveDataStore = useLiveDataStore();
  if (!liveDataStore.roomData) {
    await handleEntry(to);
  }
  if (tencentIMStore.isReady) {
    if (!liveDataStore.roomData?.openInteraction) {
      tencentIMStore.offListen();
    }
  } else if (liveDataStore.roomData?.openInteraction == 1) {
    tencentIMStore.loginChat({
      userSig: liveDataStore.roomData.userSig,
      groupID: liveDataStore.roomData.screeningId.toString()
    });
  }
  return true;
};
export {
  handleAuth,
  handleEntry,
  handleCountDown,
  handleCountDownIM,
  handleLiveIM,
  handleWatchLive,
  handleWatchLiveReplay,
  checkReplay,
  handleReplay,
  handleEntryCheck,
  handleCodeCheck
};
